extends Node2D
@export var all_player_type_map_tres: AllPlayerTypeMap
@onready var generate_map_util: GenerateMapUtil = $GenerateMapUtil
@onready var room_handler = $RoomHanlder
@onready var player_in_map = $PlayerInMap

var room_array = [1, 3, 6, 6, 12, 6, 3]
#大地图初始化完毕
signal main_map_init_success


func _ready():
	Globals.player_state = (
		all_player_type_map_tres.player_in_battle[Globals.player_type].create_instance()
	)
	Events.room_perform.connect(_on_room_perform)
	Events.goback_main_map.connect(_on_goback_main_map)
	var react = get_viewport().get_visible_rect()
	var circle_array = []
	circle_array = generate_map_util.generate_map(react.size / 2, room_array)
	draw_map(circle_array)
	main_map_init_success.emit()


func draw_map(circle_array: Array):
	for i in range(circle_array.size()):
		var one_circle_array = circle_array[i]
		for room in one_circle_array:
			if room.res != null:
				var template = room.res.duplicate()
				room_handler.add_child(template.build_room(room))
			for neighbor in room.neighbor:
				var path: Line2D = $Line2D.duplicate()
				var head = room.location + Vector2(20, 20)
				var tail = neighbor.location + Vector2(20, 20)
				var mean = (head + tail) / 2
				path.points = [head, mean, tail]
				room_handler.add_child(path)


func _on_button_pressed():
	for child in room_handler.get_children():
		room_handler.remove_child(child)
	var react = get_viewport().get_visible_rect()
	var circle_array = generate_map_util.generate_map(react.size / 2, room_array)
	draw_map(circle_array)


func _on_room_perform(_room):
	$CameraPoint/Camera2D.enabled = false


func _on_goback_main_map():
	$CameraPoint/Camera2D.enabled = true
	player_in_map.position = Globals.current_room.location.location
	Globals.current_room.perform_down()


func _on_main_map_init_success():
	if Globals.init_room != null:
		Globals.current_room = Globals.init_room
		player_in_map.position = Globals.init_room.location.location
		#var tween := create_tween()
		#tween.tween_interval(0.1)
		#tween.finished.connect(func(): Globals.init_room.location.res.perform(Globals.init_room))
